<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">
        当前位置：首页
      </el-breadcrumb-item>
      <el-breadcrumb-item>项目管理</el-breadcrumb-item>
      <el-breadcrumb-item>服务管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <div slot="header">
        <span>新增服务</span>
      </div>
      <!-- 表单 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="110px">
        <!-- 服务名称 -->
        <el-form-item label="服务名称" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入"></el-input>
        </el-form-item>
        <!-- 所属项目 -->
        <el-form-item label="所属项目" prop="project_id">
          <el-select v-model="addForm.project_id" placeholder="请选择" filterable clearable @change='selectProject'>
            <el-option v-for="item in selectData.project_list" :key="item.id" :label="item.name + '【' + item.id + '】'" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 服务类型 -->
        <el-form-item label="券类型" prop="service_type">
          <el-select v-model="addForm.service_type" @change='selectServiceType'>
            <el-option label="优惠券" value="1"> </el-option>
            <el-option label="运费券" value="2"> </el-option>
            <el-option label="兑换券" value="3"> </el-option>
          </el-select>
        </el-form-item>
        <!-- 关联服务券 -->
        <el-form-item label="关联服务券" prop="relation_id">
          <el-select v-model="addForm.relation_id" placeholder="请选择" filterable clearable @change='selectCoupon'>
            <el-option v-for="item in selectData.coupon_config_list" :key="item.id"
              :label="item.name + '【' + item.id + '】'" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 券类别 -->
        <el-form-item label="券类别" prop="category" v-show="look==false">
          <el-select v-model="addForm.category" disabled="">
            <el-option key="1" label="满减" value="1" :value="typeof addForm.type == 'string' ? '1' : 1"> </el-option>
            <el-option key="2" label="折扣" value="2" :value="typeof addForm.type == 'string' ? '2' : 2"> </el-option>
            <el-option key="3" label="特惠" value="3" :value="typeof addForm.type == 'string' ? '3' : 3"> </el-option>
          </el-select>
        </el-form-item>
        <!-- 券类型 -->
        <el-form-item label="券类型" prop="type" v-show="look==false">
          <el-select v-model="addForm.type" disabled="">
            <el-option key="1" label="专用" :value="typeof addForm.type == 'string' ? '2' : 2"> </el-option>
            <el-option key="2" label="通用" :value="typeof addForm.type == 'string' ? '1' : 1"> </el-option>
          </el-select>
        </el-form-item>
        <!-- 适用分类 -->
        <el-form-item label="适用分类" prop="apply_class">
          <el-select v-model="addForm.apply_class" placeholder="请选择" :multiple="addForm.type == 2" v-if="update" disabled="">
            <el-option v-for="item in selectData.product_type" :key="item.id" :label="item.name + '【' + item.id + '】'" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 兑换产品 -->
        <el-form-item label="兑换产品" prop="apply_class_product" v-show='look==true'
        :rules="
            look == true
              ? [
                  { required: true, message: '请选择', trigger: 'change' },
                ]
              : []
          "
        >
          <el-select v-model="addForm.apply_class_product" placeholder="请选择" multiple v-if="update" disabled="">
            <el-option v-for="item in selectData.goods" :key="item.id" :label="item.name + '【' + item.id + '】'" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 适用范围说明 -->
        <el-form-item label="适用范围说明" prop="scope_explain">
          <el-input v-model="addForm.scope_explain" placeholder="请输入，用于优惠券的商品使用限制说明(建议20字以内)"></el-input>
        </el-form-item>
        <!-- 面值 -->
        <el-form-item label="面值" prop="value" v-show="addForm.category == 1 && look==false" :rules="
            addForm.category == 1
              ? [
                  { required: true, message: '请输入', trigger: 'blur' },
                  { validator: decimalValid, trigger: 'blur' }
                ]
              : []
          ">
          <el-input placeholder="请输入" v-model="addForm.value" oninput="value=value.replace(/[^\d.]/g,'')" disabled>
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <!-- 折扣 -->
        <el-form-item label="折扣" prop="value" v-show="addForm.category == 2&&look==false" :rules="
            addForm.category == 2
              ? [
                  { required: true, message: '请输入', trigger: 'blur' },
                  { validator: decimalValid, trigger: 'blur' }
                ]
              : []
          ">
          <el-input placeholder="请输入" v-model="addForm.value" oninput="value=value.replace(/[^\d.]/g,'')" disabled>
            <template slot="append">%</template>
          </el-input>
        </el-form-item>
        <!-- 使用金额 -->
        <el-form-item label="使用金额" prop="amount" v-show="(addForm.category == 1 || addForm.category == 2 || addForm.category == 1)&&look==false" :rules="
            addForm.category == 1 || addForm.category == 2
              ? [
                  { required: true, message: '请输入', trigger: 'blur' },
                  { validator: decimalValid, trigger: 'blur' }
                ]
              : []
          ">
          <el-input placeholder="请输入" v-model="addForm.amount" oninput="value=value.replace(/[^\d.]/g,'')" disabled>
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <!-- 特惠价 -->
        <el-form-item label="特惠价" prop="value" v-show="addForm.category == 3 && look==false" :rules="
            addForm.category == 3
              ? [
                  { required: true, message: '请输入', trigger: 'blur' },
                  { validator: decimalValid, trigger: 'blur' }
                ]
              : []
          ">
          <el-input placeholder="请输入" v-model="addForm.value" oninput="value=value.replace(/[^\d.]/g,'')" disabled>
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <!-- 有效期 -->
        <el-form-item label="有效期" required>
          <el-col :span="12">
            <el-form-item prop="validity" v-show="addForm.validity_unit != 4" :rules="
                addForm.validity_unit != 4
                  ? [
                      { required: true, message: '请输入', trigger: 'blur' },
                      { type: 'number', message: '请输入数字' }
                    ]
                  : []
              ">
              <el-input placeholder="请输入" v-model.number="addForm.validity">
              </el-input>
            </el-form-item>
            <el-form-item prop="valid_start_time" v-show="addForm.validity_unit == 4" :rules="
                addForm.valid_unit == 4
                  ? [
                      {
                        required: true,
                        message: '请选择日期',
                        trigger: 'change'
                      }
                    ]
                  : []
              ">
              <el-date-picker type="date" placeholder="请选择" v-model="addForm.valid_start_time" style="width: 100%"
                value-format="yyyy-MM-dd"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="validity_unit">
              <el-select v-model="addForm.validity_unit" placeholder="请选择">
                <el-option value="1" label="日"></el-option>
                <el-option value="2" label="月"></el-option>
                <el-option value="3" label="年"></el-option>
                <el-option value="4" label="截止日期"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-form-item>
        <!-- 限制使用区域 -->
        <el-form-item label="限制使用区域" prop="is_limit">
          <el-radio v-model="addForm.is_limit" label="1" @change="handleChangeAreaLimit">限制</el-radio>
          <el-radio v-model="addForm.is_limit" label="0" @change="handleChangeAreaLimit">不限制</el-radio>
        </el-form-item>
        <!-- 限制使用区域方式 -->
        <el-form-item label="区域限制方式" prop="limit_way" v-show="addForm.is_limit == 1" :rules="
            addForm.is_limit == 1
              ? [{ required: true, message: '请选择', trigger: 'change' }]
              : []
          ">
          <el-select v-model="addForm.limit_way" placeholder="请选择" @change="changeRule">
            <el-option value="1" label="按省份"></el-option>
            <el-option value="2" label="按城市"></el-option>
          </el-select>
        </el-form-item>
        <!-- 使用区域范围 -->
        <el-form-item label="使用区域范围" prop="scope_name" v-show="addForm.is_limit == 1" :rules="
            addForm.is_limit == 1
              ? [{ required: true, message: '请选择', trigger: 'change' }]
              : []
          ">
          <el-input placeholder="请选择" v-model="addForm.scope_name">
            <el-link type="primary" slot="append" @click="openRangeDialog">选择区域</el-link>
          </el-input>
        </el-form-item>
        <!-- 使用区域描述 -->
        <el-form-item label="使用区域描述" prop="use_scope_describe">
          <el-input v-model="addForm.use_scope_describe" placeholder="请输入"></el-input>
        </el-form-item>
        <!-- 使用数量限制 -->
        <el-form-item label="使用数量限制">
          <el-col :span="12">
            <el-select v-model="addForm.use_num_unit" placeholder="请选择">
              <el-option value="" label="请选择"></el-option>
              <el-option value="1" label="每日"></el-option>
              <el-option value="2" label="每月"></el-option>
              <el-option value="3" label="每年"></el-option>
            </el-select>
          </el-col>
          <el-col :span="12">
            <el-input v-model="addForm.use_num" placeholder="请输入"></el-input>
          </el-col>
        </el-form-item>
        <!-- 使用间隔限制 -->
        <el-form-item label="使用间隔限制">
          <el-col :span="12">
            <el-select v-model="addForm.use_space_unit">
              <el-option value="" label="请选择"></el-option>
              <el-option value="1" label="日"></el-option>
            </el-select>
          </el-col>
          <el-col :span="12">
            <el-input v-model="addForm.use_space" placeholder="请输入"></el-input>
          </el-col>
        </el-form-item>
        <!-- 其他使用说明 -->
        <el-form-item label="其他使用说明" prop="other_explain">
          <el-input v-model="addForm.other_explain" placeholder="请输入"></el-input>
        </el-form-item>
        <!-- 领取渠道 -->
        <el-form-item label="领取渠道" prop="receive_way">
          <el-radio-group v-model="addForm.receive_way">
            <el-radio label="1">小程序优惠券列表</el-radio>
            <el-radio label="2">第三方系统</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 备注 -->
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="addForm.remark" show-word-limit maxlength="500"></el-input>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card style="margin-top: 10px" v-show='look==false'>
      <div slot="header">
        <span>适用商品配置</span>
      </div>
      <el-form :model="applyGoodsForm" :rules="applyGoodsFormRules" ref="applyGoodsFormRef" label-width="110px"
        label-position="left">
        <!-- 适用规则 -->
        <el-form-item label="适用规则" prop="use_rule">
          <el-radio-group @change="changeApplyFlag" v-model="applyGoodsForm.use_rule">
            <el-radio label="1" value="1">限品类</el-radio>
            <el-radio label="2" value="2">限商品</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 适用产品 -->
        <el-form-item label="适用产品" v-show="applyGoodsForm.use_rule == 1" prop="use_product" :rules="
            applyGoodsForm.use_rule == 1
              ? [{ required: true, message: '请选择', trigger: 'change' }]
              : []
          ">
          <el-checkbox-group v-model="applyGoodsForm.use_product">
            <el-checkbox v-for="item in selectData.product" :key="item.id" :label="item.id">{{ item.name }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="适用商品" v-show="applyGoodsForm.use_rule == 2" prop="use_goods" :rules="
            applyGoodsForm.use_rule == 2
              ? [{ required: true, message: '请选择', trigger: 'change' }]
              : []
          ">
          <el-checkbox-group v-model="applyGoodsForm.use_goods">
            <el-checkbox v-for="item in selectData.goods" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
    </el-card>
    <el-row style="margin-top: 10px">
      <el-button @click="$router.push('/project/Service')">
        取 消
      </el-button>
      <el-button class="theme-background-color" @click="saveInfo">保 存</el-button>
    </el-row>
    <!-- 选择省份区域对话框 -->
    <chooseMultipleProvince :provinceVisible.sync="provinceVisible" :checkedRanges="checkedRanges"
      @showProvincesData="updateRanges"></chooseMultipleProvince>

    <!-- 选择城市区域对话框 -->
    <ChooseMultipleCity :cityVisible.sync="cityVisible" :checkedRanges="checkedRanges" @showCitiesData="updateRanges">
    </ChooseMultipleCity>
  </div>
</template>

<script>
  import chooseMultipleProvince from '../region/ChooseMultipleProvince.vue'
  import ChooseMultipleCity from '../region/ChooseMultipleCity.vue'

  export default {
    components: {
      chooseMultipleProvince,
      ChooseMultipleCity
    },
    data() {
      var decimalValid = (rule, val, callback) => {
        val = val + ''
        if (val.indexOf('.') !== -1 && val.split('.').length > 2) {
          // 防止输入多个小数点
          callback(new Error('输入正确格式'))
        } else {
          // 不足补位
          val = Number(val).toFixed(2)
          // this.priceRuleForm.price = val
          this.addForm[rule.field] = val
          callback()
        }
      }
      return {
        addForm: {
          name: '',
          service_type: '',
          project_id: '',
          relation_id: '',
          category: '',
          type: '',
          apply_class: '',
          scope_explain: '',
          value: '',
          amount: '',
          preferential_price: '',
          validity: '',
          validity_unit: '',
          valid_start_time: '',
          is_limit: '0',
          limit_way: '',
          scope_name: '全国',
          use_scope: '',
          use_scope_describe: '全国',
          use_num_unit: '',
          use_num: '',
          use_space_unit: '',
          use_space: '',
          other_explain: '',
          receive_way: '',
          remark: '',
          look: false
        },
        addFormRules: {
          name: [
            { required: true, message: '请输入', trigger: 'blur' },
            { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
          ],
          service_type: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          project_id: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          category: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          type: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          apply_class: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          scope_explain: [
            { required: true, message: '请输入', trigger: 'blur' },
            { min: 2, message: '请输入最少两个字符', trigger: 'blur' }
          ],
          relation_id: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          is_limit: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          use_scope_describe: [
            { required: true, message: '请输入', trigger: 'blur' },
            { min: 2, message: '请输入最少两个字符', trigger: 'blur' }
          ],
          receive_way: [
            { required: true, message: '请选择', trigger: 'change' }
          ]
        },
        update: true, // 控制多选变化时不渲染组件，计算完再渲染组件
        selectData: {
          product_type: [],
          coupon_config_list: [],
          project_list: [],
          product: [],
          goods: []
        },
        decimalValid,

        // 省市控件勾选用的数据
        checkedRanges: [],
        provinceVisible: false,
        cityVisible: false,

        applyGoodsForm: {
          use_rule: '',
          use_product: [],
          use_goods: []
        },
        applyGoodsFormRules: {
          use_rule: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          use_product: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          use_goods: [
            { required: true, message: '请选择', trigger: 'change' }
          ]
        },
        look: false
      }
    },
    created() {
      this.getSelectData()
    },
    methods: {
      selectProject(val) {
        const arr = this.selectData.project_list
        for (var i = 0; i < arr.length; i++) {
          if (val === arr[i].id) {
            this.addForm.project_name = arr[i].name
          }
        }
      },
      async getSelectData() {
        const url = '/admin/Data/find'
        const { data: res } = await this.$http.post(url, { code: 'product_type,get_project', level: 2 })
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.selectData.product_type = res.data.product_type
        this.selectData.project_list = res.data.get_project
      },
      // 服务类型下拉框选中事件
      async selectServiceType(val) {
        const url = '/admin/Data/find'
        const { data: res } = await this.$http.post(url, { code: 'coupon_config', classify: val })
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        if (val == 3) {
          this.look = true
        } else {
          this.look = false
        }
        this.selectData.coupon_config_list = res.data.coupon_config
        this.addForm.relation_id = ''
        this.addForm.amount = ''
        this.addForm.value = ''
      },
      selectCoupon(val) {
        const arr = this.selectData.coupon_config_list
        for (var i = 0; i < arr.length; i++) {
          if (val === arr[i].id) {
            this.addForm.category = arr[i].category
            this.addForm.type = arr[i].type
            this.addForm.apply_class = arr[i].apply_class
            this.addForm.amount = arr[i].amount
            this.addForm.value = arr[i].value + ''
            this.addForm.scope_explain = arr[i].apply_explain
            this.addForm.validity_unit = arr[i].valid_unit
            if (arr[i].valid_unit == 4) {
              this.addForm.valid_start_time = arr[i].valid
            } else {
              this.addForm.validity = parseInt(arr[i].valid)
            }
            this.addForm.is_limit = arr[i].area_limit_flag + ""
            this.addForm.use_scope = arr[i].area_limit
            this.addForm.scope_name = arr[i].area_limit_name.join(',')
            this.addForm.use_scope_describe = arr[i].ranged_desc
            if (arr[i].quantity_limit == 0) {
              this.addForm.use_num = ''
            } else {
              this.addForm.use_num = arr[i].quantity_limit + ""
            }
            if (arr[i].quantity_limit_unit == '每日') {
              this.addForm.use_num_unit = '1'
            } else if (arr[i].quantity_limit_unit == '每周') {
              this.addForm.use_num_unit = '2'
            } else if (arr[i].quantity_limit_unit == '每月') {
              this.addForm.use_num_unit = '3'
            } else if (arr[i].quantity_limit_unit == '每年') {
              this.addForm.use_num_unit = '4'
            } else {
              this.addForm.use_num_unit = ''
            }
            if (arr[i].space_limit == 0) {
              this.addForm.use_space = ''
            } else {
              this.addForm.use_space = arr[i].space_limit
            }
            if (arr[i].space_limit_unit == '日') {
              this.addForm.use_space_unit = '1'
            } else {
              this.addForm.use_space_unit = ''
            }
            if (arr[i].area_limit_way === 0) {
              this.addForm.limit_way = ''
            } else {
              this.addForm.limit_way = arr[i].area_limit_way + ""
            }
            this.addForm.receive_way = arr[i].channel + ""
            this.addForm.other_explain = arr[i].explain
            this.addForm.remark = arr[i].remark
            this.applyGoodsForm.use_rule = arr[i].apply_flag + ""
            if (arr[i].apply_flag == 1) {
              this.getProductData(arr[i].apply_class)
              const arrs = arr[i].apply_value.split(',')
              for (var z = 0; z < arrs.length; z++) {
                arrs[z] = parseInt(arrs[z])
              }
              this.applyGoodsForm.use_product = arrs
            } else {
              this.getGoodsData(arr[i].apply_class)
              const arrs = arr[i].apply_value.split(',')
              for (var z = 0; z < arrs.length; z++) {
                arrs[z] = parseInt(arrs[z])
              }
              this.applyGoodsForm.use_goods = arrs
            }
            if (this.addForm.service_type == 3) {
              this.addForm.apply_class_product = arr[i].apply_value.split(',')
              for (var b = 0; b < this.addForm.apply_class_product.length; b++) {
                this.addForm.apply_class_product[b] = parseInt(this.addForm.apply_class_product[b])
              }
            }
            if (arr[i].classify == 3) {
              this.look = true
            } else {
              this.look = false
            }
            console.log(this.addForm.apply_class_product)
          }
        }
        if (this.addForm.type === 2) {
          this.addForm.apply_class = this.addForm.apply_class.split(',')
        }
      },
      handleChangeAreaLimit() {
        if (this.addForm.is_limit === '1') {
          this.addForm.use_scope_describe = ''
          this.addForm.scope_name = ''
        } else {
          this.addForm.use_scope_describe = '全国'
          this.addForm.scope_name = '全国'
        }
      },
      updateRanges(data) {
        this.addForm.use_scope = data.code.join(',')
        this.addForm.use_scope_describe = data.name.join(',')
        this.addForm.scope_name = this.addForm.use_scope_describe
      },
      changeRule() {
        // this.addForm.area_limit = ''
        this.addForm.scope_name = ''
        this.addForm.use_scope = ''
        this.addForm.use_scope_describe = ''
      },
      openRangeDialog() {
        if (this.addForm.limit_way === '') {
          this.$message({
            message: '请先选择区域限制方式',
            type: 'warning'
          })
        } else {
          if (parseInt(this.addForm.limit_way) === 1) {
            this.provinceVisible = true
          } else {
            this.cityVisible = true
          }
          // console.log(this.addForm.range_value)
          this.checkedRanges = this.addForm.use_scope
            ? this.addForm.use_scope.split(',') : []
        }
      },
      changeApplyFlag(val) {
        if (this.addForm.apply_class === '') {
          this.applyGoodsForm.use_rule = ''
          return this.$message.error('请先选择适用分类')
        }
        const typeCode =
          typeof this.addForm.apply_class === 'object'
          ? this.addForm.apply_class.join(',')
          : this.addForm.apply_class
        if (val == 1) {
          this.getProductData(typeCode)
        } else {
          this.getGoodsData(typeCode)
        }
      },
      async getProductData(typeCode) {
        const {
          data: res
        } = await this.$http.post('admin/Data/find', {
          code: 'product',
          type_code: typeCode
        })
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.selectData.product = res.data.product
      },
      async getGoodsData(typeCode) {
        const {
          data: res
        } = await this.$http.post('admin/Data/find', {
          code: 'goods',
          type_code: typeCode
        })
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.selectData.goods = res.data.goods
      },
      // 清空适用商品配置的数据
      clearApplyGoodsConfig() {
        this.$refs.applyGoodsFormRef.resetFields()
      },
      async saveInfo() {
        this.$refs.addFormRef.validate(async (valid) => {
          if (!valid) return

          this.$refs.applyGoodsFormRef.validate(async (valid2) => {
            if (!valid2) return
            const postData = JSON.parse(
              JSON.stringify(Object.assign(this.addForm, this.applyGoodsForm))
            )
            const url = 'admin/ServiceSystem/addCouponService'
            const { data: res } = await this.$http.post(url, postData)
            if (res.meta.status !== 200) {
              return this.$message.error(res.meta.msg)
            }
            this.$message.success(res.meta.msg)
            this.$router.push('/project/Service')
          })
        })
      }
    },
    computed: {
      applyValue: {
        get: function() {
          let val = ''
          if (this.applyGoodsForm.apply_flag == 1) {
            val = this.applyGoodsForm.use_product.join(',')
          } else {
            val = this.applyGoodsForm.use_goods.join(',')
          }
          return val
        },
        set: function(val) {
          if (this.applyGoodsForm.apply_flag == 1) {
            this.applyGoodsForm.use_product = val.split(',')
          } else {
            this.applyGoodsForm.use_goods = val.split(',')
          }
        }
      }
    },
    watch: {
      'addForm.type'() {
        this.update = false
        setTimeout(() => {
          this.update = true
        })
      }
    }
  }
</script>

<style lang="less" scoped>
  .el-form {
    width: 600px;
    margin-left: 15px;

    .el-select {
      width: 100%;
    }
  }
</style>
